package com.leesche.zcsp.node.app.v1.controller.sms;

import com.leesche.zcsp.node.app.v1.constants.AppContants;
import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.communication.constants.CncContants;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.utils.web.gernerator.MobileCodeGernerator;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.service.SysUserTokenService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserTokenCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserTokenDto;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/11/29 15:00: * 创建该类并实现业务逻辑: *********
 * @Title: AppSmsController.java
 * @Description: TODO(APP->短信接口)
 * @date 2016/11/29 15:00
 */
@Controller
@RequestMapping(value = "/app/v1/sms")
public class AppSmsController {
    private static final Logger logger = Logger.getLogger(AppSmsController.class);

    @Autowired
    private SmsService smsService;
    @Autowired
    private SysUserTokenService sysUserTokenService;

    /**
     * @param mobileNum 手机号码
     * @Title: sendCodeByMobile
     * @Description: TODO(按手机号码，发送短信)
     */
    @ResponseBody
    @RequestMapping(value = "sendcodebymoblie", method = RequestMethod.POST)
    public Map<String, Object> sendCodeByMobile(String mobileNum) {
        try {
            if (mobileNum == null || "".equals(mobileNum)) {
                return WebResult.failure("手机号码不能为空！").toMap();
            }

            //将该手机号作为Key值
            return beginSendMsg(mobileNum);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param token 用户令牌
     * @Title: sendSMSbyCurrenyUser(String token)
     * @Description: TODO(给当前用户手机发送短信验证码)
     * @author Jerry
     * @date 2016-10-29 04:26:57
     */
    @ResponseBody
    @RequestMapping(value = "sendcode", method = RequestMethod.POST)
    public Map<String, Object> sendSMSbyCurrenyUser(String token) {

        try {
            QuerySysUserTokenCondition condition = new QuerySysUserTokenCondition();
            condition.setToken(token);
            SysUserTokenDto sysUserTokenDto = sysUserTokenService.findUserInfoDtoByCondition(condition);
            if (sysUserTokenDto != null) {
                return beginSendMsg(sysUserTokenDto.getMobile());
            } else {
                return WebResult.failure("令牌无效，请检查令牌是否正确。").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param mobile 用户手机号
     * @param name   用户姓名
     * @Title: giveInfoAcceptSMS(String token)
     * @Description: TODO(给用户发送进件受理通知)
     * @author Jerry
     * @date 2016-10-29 04:26:57
     */
    @ResponseBody
    @RequestMapping(value = "sendAcceptNotify", method = RequestMethod.POST)
    public Map<String, Object> giveInfoAcceptSMS(String mobile, String name) {
        try {
            Map<String, String> contents = new HashMap<String, String>();
            contents.put(CncContants.KEY_CONTENT_NAME, name);
            contents.put(CncContants.KEY_CONTENT_MOBILE, mobile);
            return beginSendMsg(mobile, contents, CncContants.ALITYU_SMSTEMPLE_USERGIVEINFO_ACCEPT);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param mobile 用户手机号
     * @param name   用户姓名
     * @param result 审核结果
     * @Title: giveInfoAcceptSMS(String token)
     * @Description: TODO(给用户发送进件审核结果通知)
     * @author Jerry
     * @date 2016-10-29 04:26:57
     */
    @ResponseBody
    @RequestMapping(value = "sendResultNotify", method = RequestMethod.POST)
    public Map<String, Object> giveInfoVerifyResultSMS(String mobile, String name, String result) {
        try {
            Map<String, String> contents = new HashMap<String, String>();
            contents.put(CncContants.KEY_CONTENT_NAME, name);
            contents.put(CncContants.KEY_CONTENT_RESULT, result);
            return beginSendMsg(mobile, contents, CncContants.ALITYU_SMSTEMPLE_USERGIVEINFO_RESULT);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @param name    用户姓名
     * @param mobiles 审核员接收短信的号码组
     * @Title: giveInfoNotifySMS(String[] mobiles, String name)
     * @Description: TODO(给审核员发送客户进件通知)
     * @author Jerry
     * @date 2016-10-29 04:26:57
     */
    @ResponseBody
    @RequestMapping(value = "sendGiveInfoNotify", method = RequestMethod.POST)
    public Map<String, Object> giveInfoNotifySMS(String[] mobiles, String name) {
        try {
            Map<String, String> contents = new HashMap<String, String>();
            contents.put(CncContants.KEY_CONTENT_NAME, name);
            for (String mobile : mobiles) {
                beginSendMsg(mobile, contents, CncContants.ALITYU_SMSTEMPLE_USERGIVEINFO_ADMIN);
            }
            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param mobileNum 手机号码
     * @return 发送短信结果
     * @Title: beginSendMsg(String mobileNum, HttpSession session)
     * @Description: TODO(开始发送短信验证码)
     * @author Jerry
     * @date 2016-10-29 10:35:55
     */
    private Map<String, Object> beginSendMsg(String mobileNum) throws Exception {
        //生成随机码
        String mobileCode = MobileCodeGernerator.mobileCodeGernerator();
        //发送短信
        Message<String> smsReport = smsService.sendSMS(mobileNum, mobileCode);
        //存在到session 发送成功
        if (Message.isSuccess(smsReport.getType())) {
            //有效时间
            long validTime = new Date().getTime() + (Constants.NOTIC_DEFAULT_MOBLIE_CODE_MAXINACTIVEINTERVAL * 60000);
            //保存短信验证码
            //AppContants.PHONE_CODE.put(mobileCode, validTime);
            VaildPhone vaildPhone = new VaildPhone(validTime, mobileNum);
            PhoneCodeCacheTimer.put(mobileCode, vaildPhone);
            return WebResult.success().info(Constants.getMobileCodeVaildMsg(mobileNum)).toMap();
        } else {
            String errMag = smsReport.getContent();
            if ("InvalidRecNum.Malformed".equals(errMag)) {
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errMag)) {
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }

        }
        //记录短信发送内容
    }


    /**
     * @param mobileNum 手机号码
     * @param contents  短信内容集合
     * @param templete  短信模版
     * @return
     * @Title: beginSendMsg(String mobileNum, Map<String, String> contents, String templete)
     * @Description: TODO(发送短信)
     * @author Jerry Chan
     * @date 2016/12/28 15:36
     */
    private Map<String, Object> beginSendMsg(String mobileNum, Map<String, String> contents, String templete) throws Exception {
        Message<String> smsReport = smsService.sendSMS(mobileNum, contents, templete);
        if (Message.isSuccess(smsReport.getType())) {
            return WebResult.success().info(smsReport.getContent()).toMap();
        } else {
            String errMag = smsReport.getContent();
            if ("InvalidRecNum.Malformed".equals(errMag)) {
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errMag)) {
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }
        }
    }


}
